from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import time

class Grap:  # 类名应该以大写字母开头
    def __init__(self):
        # 确保路径正确
        self.service = Service(r"C:\Program Files\Google\Chrome\Application\chromedriver.exe") 
        self.driver = webdriver.Chrome(service=self.service)
    
    def test(self):  # 方法名使用小写字母
        self.driver.get("https://www.baidu.com")
        self.driver.get("https://www.taobao.com")
        self.driver.back()
        self.driver.forward()
        self.driver.refresh()
        print("当前页面的标题：{}".format(self.driver.title))  # 修正了格式
        print("当前页面的url：{}".format(self.driver.current_url))  # 修正了属性
        self.driver.save_screenshot("taobao.png")
        self.driver.close()  # 修正了拼写错误
        self.driver.quit()  # 修正了拼写错误

    # 通过 id 属性定位元素
    def find_id(self):
        self.driver.get("https://news.baidu.com/")
        element = self.driver.find_element(By.ID, "header-wrapper")  # 确保 ID 正确
        print(element.text)

    # 通过 class 属性
    def find_class(self):  # 修改方法名以避免重复
        self.driver.get("https://news.baidu.com/")
        element = self.driver.find_element(By.CLASS_NAME, "mod-headline-tab")  # 确保类名正确
        print(element.text)

    def click_mouse_test(self):
        self.driver.get("https://news.baidu.com/")
        self.driver.maximize_window()  # 修正了拼写错误
        element = self.driver.find_element(By.ID, "s-top-loginbtn")
        time.sleep(2)
        ActionChains(self.driver).click(on_element=element).perform()
        time.sleep(3)

    def move_to_test(self):
        self.driver.get("https://news.baidu.com/")
        self.driver.maximize_window()
        # 使用 By.XPATH 定位元素
        element = self.driver.find_element(By.XPATH, "//*[@id='s-user-setting-top']")
        ActionChains(self.driver).move_to_element(element).perform()  # 移动到元素
        time.sleep(1)  # 等待一秒以确保鼠标移动完成
        # 再次定位下拉菜单中的元素
        element1 = self.driver.find_element(By.XPATH, "//div/a[@class='setpref first']")
        ActionChains(self.driver).click(on_element=element1).perform()  # 点击该元素
        time.sleep(5)  # 等待观察结果

    def drag_and_drop_test(self):
        self.driver.get('http://portal.fuyunfeng.top/plugins_v2/index.html#/slider-verify-example')
        element = self.driver.find_element(By.ID,"circle")
        action = ActionChains(self.driver)
        action.click_and_hold(element)
        action.drag_and_drop_by_offset(element,100,0)
        time.sleep(2)
        action.perform()

if __name__ == "__main__":  # 注意这里的空格
    g = Grap()  # 类名应为 Grap
    g.drag_and_drop_test()  # 调用方法
